package com.ruoyi.common.sms;

import com.ruoyi.common.constant.Constants;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.core.domain.model.LoginKaptchaBody;
import com.ruoyi.common.utils.uuid.IdUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * 短信验证码服务
 *  redis操作
 */
@Component
public class SmsCodeRedisService {
    @Autowired
    private RedisCache redisCache;

    /**
     * 保存验证码
     * @param code
     * @return
     */
    public String saveCodeToRedis(String phoneNumber,String code){
        code = phoneNumber + code;
        String uuid = IdUtils.simpleUUID();
        String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
        redisCache.setCacheObject(verifyKey, code, Constants.CAPTCHA_EXPIRATION+3, TimeUnit.MINUTES);
        return uuid;
    }

    /**
     * 校验验证码
     * @param key uuid
     * @param phone 手机号
     * @param value 验证码
     * @param deleteFlag 校验完之后是否删除
     */
    public void checkCode(String key ,String phone ,String value, boolean deleteFlag){
        checkCode(key,phone+value,deleteFlag);
    }

    public void checkCode(String key ,String value, boolean deleteFlag){
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(key, "");
        String captcha = redisCache.getCacheObject(verifyKey);
        if (StringUtils.isEmpty(captcha) || !captcha.equals(value)) {
            throw new ServiceException("无效的验证码");
        }
        if (deleteFlag) {
            deleteCodeFromRedis(key);
        }
    }

    public void checkCode(String key ,String value){
        checkCode(key ,value,true);
    }

    /**
     * 校验验证码 默认 校验完之后删除
     * @param loginBody
     * @param deleteFlag 校验完之后是否删除
     * @return
     */
    public void checkCode(LoginKaptchaBody loginBody, boolean deleteFlag){
        checkCode(loginBody.getKaptchaKey(),loginBody.getPhoneNumber(),loginBody.getKaptchaValue(),deleteFlag);
    }

    /**
     * 校验验证码 默认校验完之后删除
     * @param loginBody
     * @return
     */
    public void checkCode(LoginKaptchaBody loginBody){
        checkCode(loginBody, true);
    }

    /**
     * 删除验证码
     * @param code
     */
    public void deleteCodeFromRedis(String code) {
        String verifyKey = Constants.CAPTCHA_CODE_KEY + StringUtils.nvl(code, "");
        redisCache.deleteObject(code);
    }

    /**
     * 删除验证码
     * @param loginBody
     */
    public void deleteCodeFromRedis(LoginKaptchaBody loginBody) {
        deleteCodeFromRedis(loginBody.getKaptchaKey());
    }
}
